package com.apexedu.portal.service.impl;


import com.alibaba.fastjson.JSON;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.portal.entity.Schedule;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.*;

/**
 * 日程安排管理
 * Created on 2015.08.18
 */
@Service("calendarService")
public class CalendarServiceImpl {

    private static final Log LOG = LogFactory.getLog(CalendarServiceImpl.class);
    @Autowired
    BaseDao baseDao;

    /**
     * 加载日期
     * @param model
     * @param user 登录用户
     * @param rq 默认日期
     * @param rq 日期
     */
    public void loadCalendar(ModelMap model,TSysUser user,String rq) throws Exception{
        if(StringUtils.isEmpty(rq)){        //如果日期为空，则用今天
            rq = DateUtil.currentDateString();
        }else{
            //判断日期格式是否正确，不正确用今天
            if(!rq.matches("\\d{4}-\\d{2}-\\d{2}")){
                rq = DateUtil.currentDateString();
            }
        }
        List<Map<String,String>> resultList = new ArrayList<Map<String, String>>();
        String sql = " select t.begintime,to_char(t.begindate,'yyyy-mm-dd') as begindate,t.title from TSCHEDULE t " +
                     " left join tuser a on t.creator=a.id where a.userid=?" +
                     " order by begindate ";
        List<Schedule> list = new DBMUtil("oa").queryAllBeanList(sql, Schedule.class, user.getUserloginid());
        if(null!=list&&list.size()>0){
            for(int i=0;i<list.size();i++){
                Schedule schedule = list.get(i);
                Map<String,String> resultMap = new LinkedHashMap<String, String>();
                resultMap.put("title",schedule.getTitle());
                resultMap.put("start",schedule.getBegindate());
                resultList.add(resultMap);
            }
        }

        String events = "[]";

        try {
            events = JSON.toJSONString(resultList);
        } catch (Exception e) {
            LOG.error(e);
        }
        model.put("events",events);

        model.put("defaultDate",rq);
    }

    /**
     * 月份每一天的事件，并标记出每天的事件
     * @param month 格式如：2015-08（yyyy-MM）
     * @return
     */
    public String monthEveryDay(String month,String userid){
        if(StringUtils.isEmpty(month)){
            month = DateUtil.formatDate(new Date(), "yyyy-MM");
        }
        List<Map<String,String>> resultList = new ArrayList<Map<String, String>>();
        try {
            String sql = " select to_char(t.begindate,'yyyy-mm-dd') as begindate,t.title from TSCHEDULE t " +
                         " left join tuser a on t.creator=a.id where to_char(begindate,'yyyy-mm')=? and a.userid=?" +
                         " order by begindate ";
             DBMUtil db= new DBMUtil("oa");
             List<Schedule> list = db.queryAllBeanList(sql, Schedule.class, month, userid);
            if(null!=list&&list.size()>0){
                for(int i=0;i<list.size();i++){
                    Schedule schedule = list.get(i);
                    Map<String,String> resultMap = new LinkedHashMap<String, String>();
                    resultMap.put("title",schedule.getTitle());
                    resultMap.put("start",schedule.getBegindate());
                    resultList.add(resultMap);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String json = "[]";

        try {
            if (resultList!=null&&resultList.size()>0) {
                json = JSON.toJSONString(resultList);
            }
        } catch (Exception e) {
            LOG.error(e);
        }

        return json;

    }

    /**
     * 获取当前今日的日程
     * @param userid 用户编号
     * @return
     */
    public String today(String userid){
        List<Map<String,String>> resultList = new ArrayList<Map<String, String>>();
        try {
            String sql = " select t.begintime,t.title,t.location from TSCHEDULE t " +
                         "  left join tuser a on t.creator=a.id where to_char(begindate,'yyyy-mm-dd')=? and a.userid=?" +
                         "  order by begintime ";
            List<Schedule> list = new DBMUtil("oa").queryAllBeanList(sql, Schedule.class,DateUtil.currentDateString(), userid);
            if(null!=list&&list.size()>0){
                for(int i=0;i<list.size();i++){
                    Schedule schedule = list.get(i);
                    Map<String,String> resultMap = new LinkedHashMap<String, String>();
                    resultMap.put("time",schedule.getBegintime());
                    resultMap.put("title",schedule.getTitle());
                    resultMap.put("place",schedule.getLocation());
                    resultList.add(resultMap);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return JSON.toJSONString(resultList);
    }

}
